package com.bristua.mall.admin.common.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.store.FifoPolicy;
import net.sf.ehcache.store.LfuPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2018/5/17 0017.
 */
@Component
public class CacheUtil {

    @Autowired
    private CacheManager cacheManager ;



    @Autowired
    private HttpServletRequest request;


    public String put(String key,Object val){
        String key2 = getKey(key);
        String key1 = key2 +"::"+getIp();
        key1 = MD5Utils.encrypt(key1.getBytes());

//        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
//        ManagementService.registerMBeans(cacheManager, mBeanServer, true, true, true, true);
//        Cache cache1 = cacheManager.getCache("856C35D4C4CD4D416141757A03A6144A");
///////////先注释
//        CacheConfiguration.CacheEventListenerFactoryConfiguration config = new CacheConfiguration.CacheEventListenerFactoryConfiguration();
//        config.setClass("net.sf.ehcache.distribution.RMICacheReplicatorFactory");
//
//        CacheConfiguration.BootstrapCacheLoaderFactoryConfiguration bootstrapCacheLoaderFactoryConfiguration = new CacheConfiguration.BootstrapCacheLoaderFactoryConfiguration();
//        bootstrapCacheLoaderFactoryConfiguration.setClass("net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory");
///////////注释结束

        CacheConfiguration cacheConfiguration = new CacheConfiguration(key1,20);

        cacheConfiguration.overflowToDisk(true)
                .eternal(false)
                .timeToLiveSeconds(3600)
                .timeToIdleSeconds(3588);

        ///////////先注释
//        cacheConfiguration.addCacheEventListenerFactory(config);
//        cacheConfiguration.addBootstrapCacheLoaderFactory(bootstrapCacheLoaderFactoryConfiguration);
///////////注释结束


//        ehCache.setMaxEntriesLocalHeap(20);
//        ehCache.setCacheName(key1);
//        cacheConfiguration.getCacheEventListenerConfigurations().add(null);
//        RMICacheReplicatorFactory rmiCacheReplicatorFactory = new RMICacheReplicatorFactory();
//        Set<CacheEventListener> cacheEventListeners = new HashSet<>();
//        RMIAsynchronousCacheReplicator rMIAsynchronousCacheReplicator = new RMIAsynchronousCacheReplicator(true,true,true,true,true,10000,1000);
//
//        cacheEventListeners.add(rMIAsynchronousCacheReplicator);
//        ehCache.setCacheEventListeners(cacheEventListeners);
//        RMIBootstrapCacheLoader rmiBootstrapCacheLoader = new RMIBootstrapCacheLoader(true,5000000);
//        ehCache.setBootstrapCacheLoader(rmiBootstrapCacheLoader);
//        cacheConfiguration.cacheEventListenerFactory(rmiCacheReplicatorFactory);
        Cache cache = new Cache(cacheConfiguration);
//        cache.setName("0D5D0D0FE1F2E1DA6D5CCCC2AB3836F3");
//        Map<String, CacheManagerPeerProvider> cacheManagerPeerProviders = cacheManager.getCacheManagerPeerProviders();
//        MulticastRMICacheManagerPeerProvider rmi = (MulticastRMICacheManagerPeerProvider)cacheManagerPeerProviders.get("RMI");
//        List list = rmi.listRemoteCachePeers(cache);
//        Cache cache = new Cache(key1, 20, false, false, 3600, 3588);
        cacheManager.addCache(cache);

        LfuPolicy lfuPolicy = new LfuPolicy();
        cache.setMemoryStoreEvictionPolicy(lfuPolicy);
        Element element = new Element(key1,val);
        cache.put(element);
        return key2;
    }


    public String put(String userName,String password,Object val){
        String key1 =  getKey(userName+password,"1");
        String key2 = key1 +"::"+getIp();
        key2 = MD5Utils.encrypt(key2.getBytes());
        Cache cache = new Cache(key2, 20, false, false, 3600, 3588);
        cacheManager.addCache(cache);
        FifoPolicy fifoPolicy = new FifoPolicy();
        cache.setMemoryStoreEvictionPolicy(fifoPolicy);
        Element element = new Element(key2,val);
        cache.put(element);
        return key1;
    }


    public Object get(String key){
        key = key+"::"+getIp();
        key = MD5Utils.encrypt(key.getBytes());
        Object element = getCacheByKey(key);
        if (element != null) return element;
        return null;
    }

    private Object getCacheByKey(String key) {
        Cache cache = cacheManager.getCache(key);
        if(cache!=null){
            Element element = cache.get(key);
            if(element!=null){
                element.setCreateTime();
                return element.getObjectValue();
            }
            cacheManager.removeCache(key);

        }
        return null;
    }




    public void remove(String key){
        cacheManager.removeCache(MD5Utils.encrypt((key+"::"+getIp()).getBytes()));
    }




    private String getKey(String key){
        return MD5Utils.encrypt(("@" + key + "@" + System.currentTimeMillis()).getBytes());
    }


    private String getKey(String key,String third){
        return MD5Utils.encrypt(("@" + key + "@" ).getBytes());
    }

//    private CacheConfiguration createCacheConfiguration(String name){
//        CacheConfiguration cacheConfiguration = new CacheConfiguration();
//        cacheConfiguration.setMaxBytesLocalHeap("");
//        cacheConfiguration.setTimeToIdleSeconds(1780);
//        cacheConfiguration.setTimeToLiveSeconds(1800);
//        cacheConfiguration.setDiskSpoolBufferSizeMB(20);
//        cacheConfiguration.setMemoryStoreEvictionPolicy("LFU");
//        cacheConfiguration.setEternal(false);
//        cacheConfiguration.setName(name);
//        return cacheConfiguration;
//    }


    /**
     * 获取用户的IP地址
     *
     * @return
     */
    private String getIp() {
        String ip = request.getHeader("X-Forwarded-For");
        if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }
}